package com.rp.common.vo;

import javax.servlet.http.HttpServletRequest;

import com.rp.common.utils.RpUtil;

/**
 * 控制器Controller中使用的分页参数类
 * @author HuangJian
 *
 */
public class PageParam {
	
	private int pageIndex;//miniui识别的页码，从0开始
	private int pageSize;
	private String sortField;
	private String sortOrder;
	
	public int getPageIndex() {
		return pageIndex;
	}
	public void setPageIndex(int pageIndex) {
		this.pageIndex = pageIndex;
	}
	public int getPageSize() {
		return pageSize;
	}
	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}
	
	public String getSortField() {
		return sortField;
	}
	public void setSortField(String sortField) {
		this.sortField = sortField;
	}
	public String getSortOrder() {
		return sortOrder;
	}
	public void setSortOrder(String sortOrder) {
		this.sortOrder = sortOrder;
	}
	
	public PageParam(HttpServletRequest request){
		this.setPageIndex(this.getIntParameter(request, "pageIndex", 0));
		this.setPageSize(this.getIntParameter(request, "pageSize", 20));
		this.setSortField(request.getParameter("sortField"));
		this.setSortOrder(request.getParameter("sortOrder"));
	}
	
	/**
	 * 获取页码，从1开始
	 * @return
	 */
	public int getPageNumber(){
		return this.pageIndex + 1;
	}
	
	/**
	 * 获取偏移量
	 * @return
	 */
	public int getPageOffset(){
		return pageIndex * pageSize;
	}
	
	/**
	 * 组装OrderBy语句
	 * @param alias 表别名
	 * @return
	 */
	public String getOrderBy(String alias){
		String orderBy = "";
		
		if(!RpUtil.isNullOrEmpty(sortField) && !RpUtil.isNullOrEmpty(sortOrder)){
			String jfinalStr = "columns.";
			String field = this.sortField;
			
			if(field.indexOf(jfinalStr) >= 0){
				field = field.substring(jfinalStr.length(), field.length());
			}
			
			orderBy = "order by " + alias + "." + field + " " + sortOrder;
		}else{
			orderBy = "order by createDate desc";
		}
		
		return orderBy;
	}
	
	private int getIntParameter(HttpServletRequest request, String parameter,
			int defaultValue) {
		String value = request.getParameter(parameter);
		if (!this.isNullString(value))
			return defaultValue;
		return Integer.parseInt(value);
	}
	
	private boolean isNullString(String string) {
		return ((null != string) && (string.length() != 0));
	}
	
	public static void main(String[] args) {
		String jfinalStr = "columns.";
		String str = "columns.title";
		str = str.substring(jfinalStr.length(), str.length());
		System.out.println(str);
	}
	
}
